package cn.sfrog.project.biz.applet.test;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;

/**
 * @Author chen
 * @Date 2023-11-29 17:00
 * @title RAS
 * @description
 **/
public class RAS {
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
        String plainText = "Hello, World!";
        System.out.println("原始文本：" + plainText);
        // 生成密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        // 将公钥传递给前端
        String s = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        System.out.println("公钥：" + s);
        String ss = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        System.out.println("公钥：" + ss);
        // 使用公钥加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedData = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        String encryptedText = Base64.getEncoder().encodeToString(encryptedData);
        System.out.println("加密后文本：" + encryptedText);
        // 使用私钥解密
        byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedText);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedData = cipher.doFinal(encryptedDataBytes);
        String decryptedText = new String(decryptedData, StandardCharsets.UTF_8);
        System.out.println("解密后文本：" + decryptedText);
    }
}
